//
// Created by chizuru on 2025/10/29.
//

//
// Created by chizuru on 2025/9/3.
//
#pragma once
#include <windows.h>
#include "xcliball.h"
#include <iostream>
#include <opencv2/opencv.hpp>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <chrono>

// 原来的单 unit 线程函数（保留不变，确保兼容 -show 的行为）
int liveThread(std::stop_token token, int unit , const std::string wname){
    // 获取图像缓冲区和分辨率信息
    int xdim = pxd_imageXdim(); // 图像宽度
    int ydim = pxd_imageYdim(); // 图像高度
    int zdim = pxd_imageZdim(); // 最大缓冲区数量
    auto bits = pxd_imageBdim();
    std::cout << "Image dimensions: " << xdim << "x" << ydim << ", Buffer depth: " << zdim << std::endl;

    // 配置缓冲区范围
    int startBuffer = 1;
    int endBuffer = zdim;

    pxd_goUnLive(unit);
    pxd_goAbortLive(unit);

    srand(time(0));
    Sleep(rand() % 1000);

    // 开始帧序列采集
    auto ret = pxd_goLiveSeq(unit, startBuffer, endBuffer / 8, 1, 0, 1);
    if (ret < 0) {
        return -1;
    }

    // 定义 OpenCV 窗口
    auto  xcapcount_buffer_start = pxd_buffersFieldCount(unit, startBuffer);
    auto xcapcount_buffer = pxd_buffersFieldCount(unit, startBuffer);

    while ((xcapcount_buffer == xcapcount_buffer_start) && (!token.stop_requested())){
        xcapcount_buffer = pxd_buffersFieldCount(unit, startBuffer);
    }

    // 统计FPS
    int frameCount = 0;
    double fps = 0.0;
    auto startTime = std::chrono::steady_clock::now();

    cv::namedWindow(wname, cv::WINDOW_AUTOSIZE);
    pxbuffer_t lastBuffer;
    while (!token.stop_requested()) {
        // 获取当前采集的缓冲区编号
        lastBuffer = pxd_capturedBuffer(unit);

        cv::Mat img = (bits == 8) ? cv::Mat(ydim, xdim, CV_8UC1)
                                  : cv::Mat(ydim, xdim, CV_16UC1);

        if (bits == 8) {
            pxd_readuchar(unit, lastBuffer, 0, 0, xdim, ydim,
                          (unsigned char*)img.data,
                          img.total() * img.elemSize(),
                          (char*)"Grey");

        } else {

            pxd_readushort(unit, lastBuffer, 0, 0, xdim, ydim,
                           (unsigned short*)img.data,
                           img.total() * img.elemSize(),
                           (char*)"Grey");

            // 转换为8bit显示
            double scale = 1.0;
            if (bits == 10) scale = 255.0 / 1023.0;
            else if (bits == 12) scale = 255.0 / 4095.0;
            else if (bits == 14) scale = 255.0 / 16383.0;

            img.convertTo(img, CV_8U, scale); // 直接覆盖 img 作为 8bit
        }

        // 统计帧率
        frameCount++;
        auto now = std::chrono::steady_clock::now();
        double elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - startTime).count();
        if (elapsed >= 1.0) {
            fps = frameCount / elapsed;
            frameCount = 0;
            startTime = now;
        }

        // 显示FPS（叠加）
        cv::Mat displayImg;
        cv::resize(img, displayImg, cv::Size(640, 480));
        cv::putText(displayImg, "FPS: " + std::to_string((int)fps),
                    cv::Point(10, 30), cv::FONT_HERSHEY_SIMPLEX,
                    .7, cv::Scalar(255, 255, 255), 2);

        cv::imshow(wname, displayImg);

        // 等待下一帧
        while (!token.stop_requested() && lastBuffer == pxd_capturedBuffer(unit)) {
            Sleep(5);
            if (!pxd_goneLive(unit, 0)) {
                pxd_mesgFault(unit);
            }
        }

        // 按 'q' 键退出
        if (cv::waitKey(1) == 'q') {
            break;
        }
    }

    // 停止采集并释放资源
    pxd_goAbortLive(unit);
    return 0;
}


